package com.ts.common.config;

import com.alibaba.fastjson.JSON;
import com.ts.animal.constant.AnimalConstant;
import com.ts.common.constant.CommonConstant;
import com.ts.common.enums.ResultCode;
import com.ts.common.utils.Result;
import com.ts.common.utils.ShiroUtils;
import com.ts.common.utils.SpringUtils;
import com.ts.common.utils.UtilString;
import com.ts.system.util.SystemUtil;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class ApiInterceptor implements HandlerInterceptor {

//    private static final Logger logger = LoggerFactory.getLogger(WebInterceptor.class);

    /*
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        arg0.setAttribute("base", "/base");
    }

    /*
     * 处理请求完成后视图渲染之前的处理操作
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();

        boolean isPage = method.getReturnType().equals(String.class);
        boolean isJosn = method.isAnnotationPresent(ResponseBody.class);
        boolean isController = (!hm.getBeanType().isAnnotationPresent(RestController.class) && hm.getBeanType().isAnnotationPresent(Controller.class));
        //controller_response_is_view 这个表示controller的返回响应类型是页面
        request.setAttribute("method_return_is_view", isPage && !isJosn && isController);

        return checkTestAccount(request, response);
    }

    final static String forbiddenUrls[] = {"update", "delete", "remove", "save", "batchRemove","resetPwd","clearDeptLabel"};

    private boolean checkTestAccount(HttpServletRequest request, HttpServletResponse response) {
        try {
            if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_check_demo_user) != null && AnimalConstant.open.equals(SystemUtil.getSystemParams().get(AnimalConstant.key_name_check_demo_user).getParamValue())) {
                String url = request.getRequestURL().toString();
                String demoUserNames[] = SystemUtil.getSystemParams().get(AnimalConstant.key_name_demo_usernames).getParamValue().split(",");
                for (String userName : demoUserNames) {
                    if (ShiroUtils.getUser() != null && userName.equals(ShiroUtils.getUser().getUsername())) {
                        for (String forbiddenUrl : forbiddenUrls) {
                            if (url.contains(forbiddenUrl)) {
                                response.setCharacterEncoding("utf-8");
                                response.setContentType("application/json; charset=utf-8");
                                PrintWriter out = null;
                                out = response.getWriter();
                                out.print(JSON.toJSONString(Result.error(Result.FAIL, "演示系统不允许修改数据,完整体验请部署程序")));
                                return false;
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

}
